package com.yekaile.carsystem.controller;

import com.yekaile.carsystem.util.Result;
import lombok.AllArgsConstructor;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author yekaile
 */
@RestController
@RequestMapping("upload")
@AllArgsConstructor(onConstructor_=@Autowired)
public class UploadController {


    HttpServletRequest request;


    @PostMapping("doUpload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return new Result<>(HttpStatus.SC_BAD_REQUEST, "上传文件为空");
        }

        String fileName = file.getOriginalFilename();
        String filePath = "D:\\phpstudy_pro\\WWW\\";
        File dest = new File(filePath + fileName);
        file.transferTo(dest);
        return new Result<>(HttpStatus.SC_CREATED, "上传成功", fileName);
    }

    @GetMapping("{fileName}.{suffix}")
    public void showPicture(@PathVariable("fileName") String fileName, @PathVariable("suffix") String suffix,
                            HttpServletResponse response) {
        String path = request.getServletContext().getRealPath("D:\\upload\\" + fileName + "." + suffix);
        File imgFile = new File(path);
        responseFile(response, imgFile);
    }

    private void responseFile(HttpServletResponse response, File imgFile) {
        try (InputStream is = new FileInputStream(imgFile);
             OutputStream os = response.getOutputStream();) {
            byte[] buffer = new byte[1024];
            while (is.read(buffer) != -1) {
                os.write(buffer);
            }
            os.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

}
